package com.zmn.mcc.admin.controller.staff.log;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.zmn.base.common.data.common.dio.company.CompanyDIO;
import com.zmn.base.common.data.common.dro.company.CompanyDRO;
import com.zmn.common.dto.LayuiTableResponseDTO;
import com.zmn.common.dto2.AMISListData;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.mcc.model.entity.staff.log.StaffLogQuery;
import com.zmn.mcc.model.entity.staff.log.StaffLogVO;
import org.apache.commons.lang.BooleanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述：师傅上下线日志ajax控制类
 *
 * @author wangjie
 * @version v1.0
 * @since 2018/12/12 19:27
 */
@RestController
@RequestMapping("/staff/log/")
public class StaffLogAjaxController extends StaffLogBaseController {

    @NacosValue(value = "${mcc.staff.log.query.enable:true}", autoRefreshed = true)
    private Boolean enable = true;

    /**
     * 描述: 异步加载表格方法
     *
     * @param query 员工操作日志查询对象
     * @return com.zmn.common.dto.LayuiTableResponseDTO
     * @author tanghongjun
     * @since 2019年7月23日17:40:14
     */
    @RequestMapping(value = "loadData")
    public LayuiTableResponseDTO loadData(StaffLogQuery query) {

        if (BooleanUtils.isFalse(enable)) {
            return new LayuiTableResponseDTO(100, "功能已关闭", null, null);
        }

        if (NumberUtil.isNullOrZero(query.getStaffId())) {
            return new LayuiTableResponseDTO(100, "请先选择员工", null, null);
        }

        List<StaffLogVO> staffLogList = staffLogBService.listPageByQuery(query);

        List<Integer> companyIds =
                staffLogList.stream().map(StaffLogVO::getCompanyId).filter(NumberUtil::isPositiveInteger).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(companyIds)) {
            CompanyDIO companyQuery = new CompanyDIO();
            companyQuery.setCompanyIds(companyIds);
            ResponseDTO<AMISListData<CompanyDRO>> responseDTO = companyListRemoteService.listPageCompanyDROByQuery(companyQuery);
            List<CompanyDRO> baseCompanyList = new ArrayList<>();
            if (responseDTO.isSuccess()) {
                baseCompanyList.addAll(responseDTO.getData().getItems());
            }
            Map<Integer, String> companyMap = baseCompanyList.stream().collect(Collectors.toMap(CompanyDRO::getCompanyId, CompanyDRO::getName));
            for (StaffLogVO staffLogVO : staffLogList) {
                if (NumberUtil.isPositiveInteger(staffLogVO.getCompanyId())) {
                    staffLogVO.setCompanyName(companyMap.get(staffLogVO.getCompanyId()));
                }
            }
        }


        return LayuiTableResponseDTO.success(query.getCount(), staffLogList);
    }
}
